<?php

namespace seecms\region\lib;

use magein\utils\Result;
use seecms\See;

class Region
{
    public function tree(array $data = null): array
    {
        if (empty($data)) {
            $data = See::db()->table('see_region')->where('status', 1)->select();
        }

        $map = [];
        $tree = [];

        // 第一遍：初始化所有节点
        foreach ($data as $item) {
            $map[$item['code']] = [
                'code' => $item['code'],
                'name' => $item['name'],
                'pinyin' => $item['pinyin'],
                'first_char' => $item['first_char'],
                'children' => []
            ];
        }

        // 第二遍：构建父子关系
        foreach ($data as $item) {
            $node = &$map[$item['code']];
            if ($item['parent_code'] ?? '') {
                if (isset($map[$item['parent_code']])) {
                    $map[$item['parent_code']]['children'][] = &$node;
                }
            } else {
                $tree[] = &$node;
            }
        }

        return $tree;
    }

    /**
     * @param array $data
     * @param string $filepath
     * @return Result
     */
    public function saveJson(array $data = [], string $filepath = ''): Result
    {
        if (empty($data)) {
            $data = $this->tree($data);
        }

        if (empty($filepath)) {
            $filepath = See::config()->vendor->root() . 'vendor' . DIRECTORY_SEPARATOR . 'region';
        }

        if (!is_dir($filepath)) {
            return Result::error('save region filepath fail');
        }

        $filepath = $filepath . '/chain_region.js';
        if (is_file($filepath)) {
            return Result::error('chain_region.js filepath exist');
        }

        file_put_contents($filepath, 'const _chain_region=' . json_encode($data, JSON_UNESCAPED_UNICODE) . ';');

        return Result::success(See::config()->vendor->assetStatic(), 'save region filepath success');
    }
}